import {
	baseUrl
} from './config'



let post = function(url, data={}, simple = true) {
	return new Promise(async (resolve, reject) => {
		uni.request({
			url: `${baseUrl}${url}`,
			method: 'POST',
			data,
			...await getConfig(),
			success: res => {
				if(re_getToken(res)){
					reject(res)
				}
				if (simple) {
					resolve(res.data)
				} else {
					resolve(res)
				}
			},
			fail: res => {
				reject(res)
			}
		});
	})

}
let get = function(url, data={}, simple = true) {
	return new Promise( async (resolve, reject) => {
		uni.request({
			url: `${baseUrl}${url}`,
			method: 'GET',
			data,
			...await getConfig(),
			success: res => {
				if(re_getToken(res)){
					reject(res)
				}
				
				if (simple) {
					resolve(res.data)
				} else {
					resolve(res)
				}
			},
			fail: res => {
				reject(res)
			}
		});
	})

}

let upload = function(url, filePath) {
	return new Promise( async (resolve, reject) => {
		let cfg = await getConfig();
		cfg.header['content-type']='application/x-www-form-urlencoded';
		uni.uploadFile({
			url: `${baseUrl}${url}`,
			filePath,
			name:'file',
			...cfg,
			// timeout:'',
			success: res => {
				if(re_getToken(res)){
					reject(res)
				}
				resolve(res)
			},
			fail: res => {
				reject(res)
			}
		});
	})

}


function setConfig(data) {
	uni.setStorage({
		key: 'config',
		data,
	});
}

async function getConfig() {
	return uni.getStorageSync('config') || await getToken();
}

function re_getToken(res){
	try{
		if(res.data.code == 403){
			uni.showModal({
				title: '提示',
				content: '登录失效',
				confirmText:'重新登录',
				showCancel:false,
			});
			getToken();
			return true
		}else{
			return false
		}
	}catch(e){
	}
}
async function getToken() {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: "weixin",
			success:  res => {
				uni.request({
					url: `${baseUrl}/api/user/auth`,
					method: 'POST',
					data:{
						code:res.code,
					},
					success: data => {
						let token = data.data.data.token;
						setConfig({
							header: {
							    'Authorization': token
							},
						})
						resolve({
							header: {
								'Authorization': token 
							},
						})
						
					},
				});
			}
		})
		
		
	})
}
getToken();

let req = {
	post,
	get,
	setConfig,
	getConfig,
	upload
};

export default req;